package top.cluski.tokendemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import top.cluski.tokendemo.domain.LoginUser;
import top.cluski.tokendemo.domain.User;
import top.cluski.tokendemo.mapper.SysMenuMapper;
import top.cluski.tokendemo.mapper.UserMapper;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private SysMenuMapper sysMenuMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, username);
        User user = userMapper.selectOne(queryWrapper);
        // 如果没有查询到用户，抛出异常
        if (Objects.isNull(user)) {
            throw new UsernameNotFoundException("用户名或者密码错误");
        }

        // 从数据库中查询权限信息
        List<String> permissions = sysMenuMapper.selectPermsByUserId(user.getId());
//        List<String> permissions = new ArrayList<>(Arrays.asList("test", "admin"));

        return new LoginUser(user, permissions);
    }
}
